#include <netinet/in.h>
#include "Log.hpp"
#include <sys/types.h>
#include <sys/socket.h>
#include <strings.h>
#include <istream>
#include <string>
#include <arpa/inet.h>

using namespace LogModule;

class UdpClient
{
public:
    UdpClient(std::string ip, int port)
        : _ip(ip), _port(port), _isrunning(false)
    {
    }

    void Init()
    {
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(LogLevel::ERROR) << "socket create failed";
        }
        LOG(LogLevel::ERROR) << "socket create success";
    }
   
    void Start()
    {
        _isrunning = true;
        struct sockaddr_in server;
        bzero(&server, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_addr.s_addr = inet_addr(_ip.c_str());
        server.sin_port = inet_addr(_ip.c_str());
        while (_isrunning)
        {
            char buffer[1024];
            bzero(buffer, sizeof(buffer));
            std::string message ;
            std::cout << "Plase Enter@:";
            std::getline(std::cin, message);
            sendto(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&server, sizeof(server));
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t ret = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &len);
            if (ret < 0)
            {
                LOG(LogLevel::ERROR) << " Client recvfrom failed";
            }
            buffer[ret] = 0;
            std::cout << "Server say#:" << buffer << std::endl;
        }
    }

    ~UdpClient()
    {
    }

private:
    int _sockfd;
    bool _isrunning;
    std::string _ip;
    int _port;
};